package config

import "github.com/spf13/viper"

var cfg *Config

type Config struct {
	App App `mapstructure:"app"`
}

type App struct {
	Name        string   `mapstructure:"name"`
	Version     string   `mapstructure:"version"`
	Description string   `mapstructure:"description"`
	Web         Web      `mapstructure:"web"`
	Database    Database `mapstructure:"database"`
	Redis       Redis    `mapstructure:"redis"`
	Mqtt        Mqtt     `mapstructure:"mqtt"`
	Log         Log      `mapstructure:"log"`
	Mq          Mq       `mapstructure:"mq"`
	Wechat      Wechat   `mapstructure:"wechat"`
	Alipay      Alipay   `mapstructure:"alipay"`
}

type Web struct {
	Port int      `mapstructure:"port"`
	Url  string   `mapstructure:"url"`
	Cors []string `mapstructure:"cors"`
}

type Database struct {
	Host     string `mapstructure:"host"`
	Port     int    `mapstructure:"port"`
	User     string `mapstructure:"user"`
	Password string `mapstructure:"password"`
	Name     string `mapstructure:"name"`
}

type Redis struct {
	Host     string `mapstructure:"host"`
	Port     int    `mapstructure:"port"`
	Password string `mapstructure:"password"`
	Db       int    `mapstructure:"db"`
}

type Mqtt struct {
	Host     string `mapstructure:"host"`
	Port     int    `mapstructure:"port"`
	User     string `mapstructure:"user"`
	Password string `mapstructure:"password"`
}

type Log struct {
	Level  string `mapstructure:"level"`
	Format string `mapstructure:"format"`
	Output string `mapstructure:"output"`
}

type Mq struct {
	Host string `mapstructure:"host"`
	Port int    `mapstructure:"port"`
}

type Wechat struct {
	Official Official `mapstructure:"official"`
	Mini     Mini     `mapstructure:"mini"`
}

type Official struct {
	AppId  string `mapstructure:"app_id"`
	Secret string `mapstructure:"secret"`
	AesKey string `mapstructure:"aes_key"`
	Token  string `mapstructure:"token"`
}

type Mini Official

type Alipay struct {
	AppId      string `mapstructure:"app_id"`
	PrivateKey string `mapstructure:"private_key"`
	PublicKey  string `mapstructure:"public_key"`
	ReturnUrl  string `mapstructure:"return_url"`
	NotifyUrl  string `mapstructure:"notify_url"`
}

func Init() {
	v := viper.New()
	v.SetConfigType("yaml")
	v.SetConfigName("config")
	v.AddConfigPath(".")
	if err := v.ReadInConfig(); err != nil {
		panic(err)
	}

	cfg = &Config{}
	if err := v.Unmarshal(cfg); err != nil {
		panic(err)
	}
}

func Instance() *Config {
	return cfg
}
